package com.yunxi.controller.customer;

import com.yunxi.common.config.OSSUtil;
import com.yunxi.core.util.ExportExcel;
import com.yunxi.core.util.GUIDGenerator;
import com.yunxi.core.util.MyZipUtils;
import com.yunxi.core.web.ApiResult;
import com.yunxi.core.web.CurrentUser;
import com.yunxi.core.web.LoginInfo;
import com.yunxi.core.web.ResponseUtil;
import com.yunxi.customer.pojo.CustomCreditExportVO;
import com.yunxi.customer.pojo.CustomCreditReportingVO;
import com.yunxi.customer.service.CustomCreditReportingDubboService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Field;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 个人征信信息表 前端控制器
 * </p>
 *
 * @author
 * @since 2019-08-20
 */
@Controller
@RequestMapping("/admin/customcreditreporting")
@Api(tags = "pms:customcreditreporting", description = "个人征信信息表接口")
public class CustomCreditReportingController {
   private static final Logger logger = LoggerFactory.getLogger(CustomCreditReportingController.class);

   @Autowired
   CustomCreditReportingDubboService customCreditReportingDubboService;

   @Value("${spring.profiles.active}")
   public String ENV;

   @GetMapping("/page")
   @ResponseBody
   @ApiOperation(value = "查询征信分页")
   public ApiResult page(CustomCreditReportingVO customCreditReportingVO, Integer pageNum, Integer pageSize, @CurrentUser LoginInfo loginInfo) throws Exception {
      return ResponseUtil.ok(customCreditReportingDubboService.findPageByVO(customCreditReportingVO, pageNum, pageSize,loginInfo));
   }

   @GetMapping("/list")
   @ResponseBody
   @ApiOperation(value = "查询征信列表")
   public ApiResult list(CustomCreditReportingVO customCreditReportingVO) throws Exception {
      return ResponseUtil.ok(customCreditReportingDubboService.listByVo(customCreditReportingVO));
   }

   @GetMapping("/load")
   @ResponseBody
   @ApiOperation(value = "读取单个征信")
   public ApiResult load(CustomCreditReportingVO customCreditReportingVO, @CurrentUser LoginInfo loginInfo) throws Exception {
      return ResponseUtil.ok(customCreditReportingDubboService.getById(customCreditReportingVO.getCreditId()));
   }

   @PostMapping("/save")
   @ResponseBody
   @ApiOperation(value = "保存征信信息")
   public ApiResult save(@RequestBody CustomCreditReportingVO customCreditReportingVO, @CurrentUser LoginInfo loginInfo) throws Exception {

      return customCreditReportingDubboService.saveOrUpdate(customCreditReportingVO,loginInfo);
   }

   @PostMapping("/updateBatch")
   @ResponseBody
   @ApiOperation(value = "批量审核")
   public ApiResult save(@RequestBody List<CustomCreditReportingVO> list, @CurrentUser LoginInfo loginInfo) throws Exception {

      return customCreditReportingDubboService.updateBatch(list,loginInfo);
   }

   @PostMapping("/del")
   @ResponseBody
   @ApiOperation(value = "删除征信")
   public ApiResult del(@RequestBody List<CustomCreditReportingVO> customCreditReportingVOList) throws Exception {
      customCreditReportingDubboService.removeByListVo(customCreditReportingVOList);
      return ResponseUtil.ok("success");
   }

//   @PostMapping("/exportDetailDate")
//   @ResponseBody
//   @ApiOperation(value = "导出详情")
//   public ApiResult exportDetailDate(@RequestBody List<CustomCreditReportingVO> voList) throws Exception {
//      return ResponseUtil.ok(customCreditReportingDubboService.exportDetailDate(voList));
//   }

//   @PostMapping("/exportDetail")
//   @ResponseBody
//   @ApiOperation(value = "导出详情excel")
//   public ModelAndView export(@RequestBody List<CustomCreditReportingVO> voList,HttpServletResponse response) throws Exception {
//      List<CustomCreditExportVO> customCreditExportVOS = customCreditReportingDubboService.exportDetailDate(voList);
//      if (customCreditExportVOS==null || customCreditExportVOS.size()<=0) return null;
//      //domain的实体类(该实体类如果作为最终导出结果的实体类,则该类的字段必须与需要导出的字段保持一致,且与导出列表的顺序也得保持一致)
//      ExportExcel<CustomCreditExportVO> ex = new ExportExcel<>();
//      String[] headers = { "客户类型","审核状态","客户姓名","性别","婚姻状况" ,"证件类型" ,"身份证号" ,"手机号" ,"现居住地址" ,"单位名称" ,"工作单位地址" ,"紧急联系人" ,"与申请人关系" ,"紧急联系人手机" ,"配偶姓名" ,"配偶手机" ,"配偶身份证" ,"配偶现居住地址" ,"配偶单位名称" ,"配偶工作单位地址" ,"公司名称" ,"公司固话" ,"公司联系人电话" ,"公司办公地址" ,"公司法人代表" ,"公司法人性别" ,"公司法人手机号码" ,"开票信息" ,"担保人姓名" ,"担保人与申请人关系" ,"担保人手机" ,"担保人证件号" ,"担保人现居住地址" ,"担保人单位名称" ,"担保人工作单位地址" ,"(企业客户)紧急联系人" ,"(企业客户)与申请人关系" ,"(企业客户)紧急联系电话","订单编号" ,"金融机构","产品类型" ,"车辆申请时间" ,"车型" ,"车辆金额(发票价)","车辆申请区域" ,"成交价格" ,"附件包" ,"GPS价格" ,"融资租赁合同金额" ,"首付比例" ,"首付金额" ,"保证金比例" ,"保证金金额" ,"留购价比例" ,"留购价金额" ,"融资本金" ,"融资年利率" ,"直租牌照费用" ,"月租金","租赁期限" ,"创建时间" };
//      String[] fileNames = { "个人征信信息" };
//      ex.exportExcel(headers,customCreditExportVOS,fileNames,response);
//      return null;
//   }
   private static String filePath;

   static {
      try {
         filePath = URLDecoder.decode(CustomCreditReportingController.class.getResource("/").getPath(), "utf-8");
      } catch (UnsupportedEncodingException e) {
         e.printStackTrace();
      }
   }

   @Autowired
   OSSUtil ossUtil;

   @PostMapping("/exportZip")
   @ApiOperation(value = "导出exportZip")
   public ModelAndView exportZip(@RequestBody List<CustomCreditReportingVO> voList, HttpServletResponse response) throws Exception {
//      customCreditReportingDubboService.exportZip(voList,response);
      String derectoryName = filePath + "征信信息"+System.currentTimeMillis()+ GUIDGenerator.getPrimaryKey();
      //创建图片文件夹
      System.out.println("文件夹全路径:"+derectoryName);
      File file = new File(derectoryName);
      if (!file.exists()) {//如果文件夹不存在
         file.mkdir();//创建文件夹
      }

      List<CustomCreditExportVO> customCreditExportVOS = customCreditReportingDubboService.exportDetailDate(voList);
      if (customCreditExportVOS==null || customCreditExportVOS.size()<=0) return null;

      //domain的实体类(该实体类如果作为最终导出结果的实体类,则该类的字段必须与需要导出的字段保持一致,且与导出列表的顺序也得保持一致)
      String[] headers = { "金融类型","客户类型","审核状态","是否自备牌照","客户姓名","性别","手机号" ,"证件类型" ,"证件号码","居住省","居住地级市","现居住地址","户口所在地","婚姻状况","身份证号","学历","单位名称" ,"工作单位地址" ,"单位所在地级市","单位所在省","紧急联系人" ,"紧急联系人手机","与紧急联系人关系","居住状况","主要税后年收入","配偶姓名" ,"配偶手机" ,"配偶身份证" ,"配偶现居住地址" ,"配偶单位名称" ,"配偶工作单位地址" ,"公司名称","企业代码","公司固话","企业性质" ,"公司联系人姓名","公司联系人电话" ,"公司办公地址" ,"公司办公城市","公司法人代表" ,"公司法人性别" ,"公司法人手机号码","纳税人类型","发票抬头","纳税人识别号","发票开户行","发票开户账号","开票地址","开票电话","发票寄送地点","开票信息" ,"担保人姓名" ,"担保人与申请人关系" ,"担保人手机" ,"担保人证件号" ,"担保人现居住地址" ,"担保人现居城市","担保人单位名称" ,"担保人工作单位地址","担保人工作城市" ,"(企业客户)紧急联系人" ,"(企业客户)与申请人关系" ,"(企业客户)紧急联系电话","订单编号" ,"金融机构","产品类型" ,"车辆申请时间" ,"车型" ,"车辆金额(发票价)","车辆申请区域" ,"分期情况","首付比例","保证金比例","留购价比例","留购价金额","总价格","利率","费率","贴息类型","贴息值","牌照管理费" ,"创建时间" };
      String[] fileNames = { "征信信息表" };
      ExportExcel<CustomCreditExportVO> ex = new ExportExcel<>();
      ex.exportExcel(headers,customCreditExportVOS,fileNames,response,derectoryName);

      System.out.println("开始下载"+new SimpleDateFormat("yyyyMMdd HH:mm:ss").format(new Date()));

      //下载图片到文件夹中
      if (voList!=null && voList.size()>0){
         downloadImg(voList, derectoryName);
      }

      //打压缩包到项目中
      MyZipUtils myZipUtils = new MyZipUtils();
      //压缩包名
      String fileName = "pic" +"征信图片" + ".zip";
      //压缩包全路径
      String zipPath = filePath + "zipDerectory" +"/"+ fileName;
      File zipFile = new File(filePath + "zipDerectory");
      if (!zipFile.exists()) {//如果文件夹不存在
         zipFile.mkdir();//创建文件夹
      }
      try {
         myZipUtils.doCompress(derectoryName, zipPath);
         System.out.println("压缩包路径:"+zipPath);
      } catch (IOException e) {
         e.printStackTrace();
      }

      //压缩包输出到客户端浏览器
      try {
         myZipUtils.downloadZipFile(response, zipPath, fileName);
      } catch (IOException e) {
         e.printStackTrace();
      }finally {
         myZipUtils.delFile(file);
         myZipUtils.delFile(zipFile);
      }
      System.out.println("结束下载" +new SimpleDateFormat("yyyyMMdd HH:mm:ss").format(new Date()) );
      return null;
   }

   private void downloadImg(@RequestBody List<CustomCreditReportingVO> voList, String derectoryName) throws Exception {
      for (CustomCreditReportingVO customCreditReportingVO : voList) {
         List<CustomCreditReportingVO> list = customCreditReportingDubboService.listByVo(customCreditReportingVO);
         if (list!=null && list.size()>0){
            for (CustomCreditReportingVO creditReportingVO : list) {
               String picDerectoryName = "";
               if ("1".equals(creditReportingVO.getCustomerType()) ){
                  picDerectoryName= derectoryName+"/"+creditReportingVO.getName()+creditReportingVO.getPhone()+"pic";
               }else if ("2".equals(creditReportingVO.getCustomerType()) ){
                  picDerectoryName= derectoryName+"/"+creditReportingVO.getCompany()+creditReportingVO.getCompanyLinkPhone()+"pic";
               }else {
                  picDerectoryName = derectoryName+"/"+creditReportingVO.getCreditCode();
               }

               System.out.println("图片文件夹全路径:"+picDerectoryName);

               if ("dev".equals(ENV) || "test".equals(ENV)){
                  //OSS下载图片到该文件夹中
                  List<String> objectNames = new ArrayList<>();
                  List<String> attachUrlList = new ArrayList<>();
                  if (StringUtils.isNotEmpty(creditReportingVO.getIdImgPath1())){
                     attachUrlList.add(creditReportingVO.getIdImgPath1());
                     objectNames.add(creditReportingVO.getIdImgPath1().substring(creditReportingVO.getIdImgPath1().lastIndexOf(".com") + 5));
                  }
                  if (StringUtils.isNotEmpty(creditReportingVO.getIdImgPath2())){
                     attachUrlList.add(creditReportingVO.getIdImgPath2());
                     objectNames.add(creditReportingVO.getIdImgPath2().substring(creditReportingVO.getIdImgPath2().lastIndexOf(".com") + 5));
                  }
                  if (StringUtils.isNotEmpty(creditReportingVO.getLicenseImgPath1())){
                     attachUrlList.add(creditReportingVO.getLicenseImgPath1());
                     objectNames.add(creditReportingVO.getLicenseImgPath1().substring(creditReportingVO.getLicenseImgPath1().lastIndexOf(".com") + 5));
                  }
                  if (StringUtils.isNotEmpty(creditReportingVO.getLicenseImgPath2())){
                     attachUrlList.add(creditReportingVO.getLicenseImgPath2());
                     objectNames.add(creditReportingVO.getLicenseImgPath2().substring(creditReportingVO.getLicenseImgPath2().lastIndexOf(".com") + 5));
                  }
                  if (StringUtils.isNotEmpty(creditReportingVO.getBankReordPath())){
                     attachUrlList.add(creditReportingVO.getBankReordPath());
                     objectNames.add(creditReportingVO.getBankReordPath().substring(creditReportingVO.getBankReordPath().lastIndexOf(".com") + 5));
                  }
                  if (StringUtils.isNotEmpty(creditReportingVO.getPremisesPermitPath1())){
                     attachUrlList.add(creditReportingVO.getPremisesPermitPath1());
                     objectNames.add(creditReportingVO.getPremisesPermitPath1().substring(creditReportingVO.getPremisesPermitPath1().lastIndexOf(".com") + 5));
                  }
                  if (StringUtils.isNotEmpty(creditReportingVO.getPersonCreditPic())){
                     attachUrlList.add(creditReportingVO.getPersonCreditPic());
                     objectNames.add(creditReportingVO.getPersonCreditPic().substring(creditReportingVO.getPersonCreditPic().lastIndexOf(".com") + 5));
                  }
                  if (StringUtils.isNotEmpty(creditReportingVO.getBusinessLicensePic())){
                     attachUrlList.add(creditReportingVO.getBusinessLicensePic());
                     objectNames.add(creditReportingVO.getBusinessLicensePic().substring(creditReportingVO.getBusinessLicensePic().lastIndexOf(".com") + 5));
                  }
                  if (StringUtils.isNotEmpty(creditReportingVO.getSuretyCreditPic())){
                     attachUrlList.add(creditReportingVO.getSuretyCreditPic());
                     objectNames.add(creditReportingVO.getSuretyCreditPic().substring(creditReportingVO.getSuretyCreditPic().lastIndexOf(".com") + 5));
                  }
                  ossUtil.downloadOSS(attachUrlList,objectNames,picDerectoryName);
               }else {
                  ArrayList<String> urlList = new ArrayList<>();
                  if (StringUtils.isNotEmpty(creditReportingVO.getIdImgPath1())){
                     urlList.add(creditReportingVO.getIdImgPath1());
                  }
                  if (StringUtils.isNotEmpty(creditReportingVO.getIdImgPath2())){
                     urlList.add(creditReportingVO.getIdImgPath2());
                  }
                  if (StringUtils.isNotEmpty(creditReportingVO.getLicenseImgPath1())){
                     urlList.add(creditReportingVO.getLicenseImgPath1());
                  }
                  if (StringUtils.isNotEmpty(creditReportingVO.getLicenseImgPath2())){
                     urlList.add(creditReportingVO.getLicenseImgPath2());
                  }
                  if (StringUtils.isNotEmpty(creditReportingVO.getBankReordPath())){
                     urlList.add(creditReportingVO.getBankReordPath());
                  }
                  if (StringUtils.isNotEmpty(creditReportingVO.getPremisesPermitPath1())){
                     urlList.add(creditReportingVO.getPremisesPermitPath1());
                  }
                  if (StringUtils.isNotEmpty(creditReportingVO.getPersonCreditPic())){
                     urlList.add(creditReportingVO.getPersonCreditPic());
                  }
                  if (StringUtils.isNotEmpty(creditReportingVO.getBusinessLicensePic())){
                     urlList.add(creditReportingVO.getBusinessLicensePic());
                  }
                  if (StringUtils.isNotEmpty(creditReportingVO.getSuretyCreditPic())){
                     urlList.add(creditReportingVO.getSuretyCreditPic());
                  }

                  ossUtil.download2(urlList,picDerectoryName);
               }

            }
         }
      }
   }


/*@PostMapping("/export")
@ApiOperation(value = "导出excel")
public Object export(@RequestParam Map<String,Object> params) throws Exception {
return ResponseUtil.ok(customCreditReportingDubboService.findMapByList(params));
}*/
}
